package com.android.readcard.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.android.readcard.R;
import com.android.readcard.inter.SearchBleResult;
import com.android.readcard.adapter.BleAdapter;

import java.util.ArrayList;
import java.util.Set;

/**
 * 蓝牙设备弹窗
 * 2017.8.24
 * 张鹏
 */
public class BleDialog extends Dialog {
    private Context mContext;
    private Activity activity;
    private int index;
    private BluetoothAdapter ba;
    private String str;
    private BluetoothDevice remoteDevice;
    private ProgressBar pb_ble;
    private SearchBleResult mSearchBleResult;
    private ArrayList<String> bleNameList = new ArrayList<>();
    private ArrayList<String> bleAddressList = new ArrayList<>();
    private BleAdapter bleAdapter;
    // 配对弹窗监听
    private ListView lv_ble;
    private String bleAddress;
    private String bleName;

    public BleDialog(Context context, BluetoothAdapter ba,
                     int index, String str, SearchBleResult mSearchBleResult) {
        super(context, R.style.BtDialogStyle);
        this.mContext = context;
        this.activity = (Activity) context;
        this.ba = ba;
        this.index = index;
        this.str = str;
        this.mSearchBleResult = mSearchBleResult;
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bledialog);
        lv_ble = (ListView) findViewById(R.id.lv_ble);
        pb_ble = (ProgressBar) findViewById(R.id.pb_ble);
        lv_ble.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (index == 6) {
                    pb_ble.setVisibility(View.GONE);
                    ba.stopLeScan(mLeScanCallback);
                }

                if (bleAdapter.getCount() > 0) {
                    // 触发连接监听
                    String item = bleAdapter.getItem(position);
                    bleAddress = bleAddressList.get(position);
                    bleName = bleNameList.get(position);
                    remoteDevice = ba.getRemoteDevice(bleAddressList.get(position));
                    if (index == 0) {
                        // 华视读卡
                        mSearchBleResult.searchSuc(index, bleAddress, bleName, remoteDevice);
                    } else {
                        if (item.contains(str)) {
                            mSearchBleResult.searchSuc(index, bleAddress, bleName, remoteDevice);
                        } else {
                            mSearchBleResult.searchErr("请选择正确的配对设备");
                        }
                    }
                } else {
                    mSearchBleResult.searchErr("扫描异常,请重新扫描");
                }
                cancel();
            }
        });


        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);
    }

    //*************************************************************************************************************

    @Override
    public void show() {
        super.show();
        bleNameList = new ArrayList<>();
        bleAddressList = new ArrayList<>();
        bleAdapter = new BleAdapter(activity, bleNameList);
        lv_ble.setAdapter(bleAdapter);
        if (index == 6) {
            // 蓝牙搜索
            scanLeDevice(true);
        } else {
            // 配对搜索
            SearchBts();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        bleNameList.clear();
        bleAddressList.clear();
        if (mLeScanCallback != null) {
            // 触发消失监听
            ba.stopLeScan(mLeScanCallback);
        }
        dismiss();
        activity.finish();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        bleNameList.clear();
        bleAddressList.clear();
        if (mLeScanCallback != null) {
            // 触发消失监听
            ba.stopLeScan(mLeScanCallback);
        }
    }

    @Override
    public void cancel() {
        super.cancel();
        bleNameList.clear();
        bleAddressList.clear();
        if (mLeScanCallback != null) {
            // 触发消失监听
            ba.stopLeScan(mLeScanCallback);
        }
    }

    /**
     * 搜索已配对蓝牙
     */
    private void SearchBts() {
        String strName = "";
        Set<BluetoothDevice> pairedDevices = ba.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                Log.e("蓝牙异常mLeScanCallback", "[" + device.getName() + "]"
                        + "已配对:" + device.getAddress());
                strName += device.getName();
                // 检测配对设备,如果包含制定字符串就去连接读卡器
                bleNameList.add(device.getName());
                bleAddressList.add(device.getAddress());
                bleAdapter.notifyDataSetChanged();
            }
            pb_ble.setVisibility(View.GONE);
            if (!strName.contains(str)) {
                dismiss();
                // 配对弹窗
                mSearchBleResult.onSetDialog();
            }
        } else {
            dismiss();
            // 配对弹窗
            mSearchBleResult.onSetDialog();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pb_ble.setVisibility(View.GONE);
            ba.stopLeScan(mLeScanCallback);
        }
    };

    private static final long SCAN_PERIOD = 8000;

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ba.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            ba.startLeScan(mLeScanCallback);
        } else {
            pb_ble.setVisibility(View.GONE);
        }
    }

    /**
     * 搜索蓝牙(djlm)
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    Log.e("蓝牙异常mLeScanCallback", "[" + device.getName() + "]"
                            + "搜索:" + device.getAddress());
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pb_ble.setVisibility(View.VISIBLE);
                            Boolean judge = false;
                            Log.e("蓝牙异常mLeScanCallback", "[" + device.getName() + "]"
                                    + "搜索:" + device.getAddress());
                            mHandler.sendEmptyMessageDelayed(0, 6000);
                            if (bleNameList != null && bleNameList.size() > 0) {
                                if (bleNameList.size() < 6) {
                                    if (device.getName() != null
                                            && !"null".equals(device.getName())
                                            && !TextUtils.isEmpty(device.getName())) {
                                        for (String s : bleNameList) {
                                            if (s != null && !"null".equals(s) && !TextUtils.isEmpty(s)) {
                                                if (s.contains(device.getName())) {
                                                    judge = true;
                                                }
                                            }
                                        }
                                        if (!judge) {
                                            bleNameList.add(device.getName());
                                            bleAddressList.add(device.getAddress());
                                            bleAdapter.notifyDataSetChanged();
                                        }
                                    }
                                } else {
                                    pb_ble.setVisibility(View.GONE);
                                    ba.stopLeScan(mLeScanCallback);
                                }
                            } else {
                                if (device.getName() != null
                                        && !"null".equals(device.getName())
                                        && !TextUtils.isEmpty(device.getName())) {
                                    bleNameList.add(device.getName());
                                    bleAddressList.add(device.getAddress());
                                    bleAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    });
                }
            };
}